var status;
var index;
var intervalID;
var prevReq;
var reqDelay = 60;

function doNext() {
	if (status == "stop")
		return;

	if (status == "list") {
		var time = new Date();
		if (typeof(prevReq) == "object" && time - prevReq < reqDelay * 1000) {
			return;
		}

		var list = document.getElementsByClassName("char-wrapper")[0].children;
		var item = list[index];
		if (item == null) {
			status = "stop";
			window.clearInterval(intervalID);
			return;
		};

		var text = document.getElementsByClassName('player_num')[0].children[1].innerHTML;
		if (text == "0" || text == "1") {
			item.click();
			console.log("Requested click on char " + index);
			status = "wait_quantity";
			return;
		};
	};

	if (status == "wait_quantity") {
		var text = document.getElementsByClassName('player_num')[0].children[1].innerHTML;
		// console.log(text);
		if (text == "0") {
			status = "list";
			index = index + 1;
		} else if (text == "1") {
			var claim = document.getElementById('goAward').children[0];
			claim.click();
			status = "wait_result";
			prevReq = new Date();
		};
	};

	if (status == "wait_result") {
		var box = document.getElementsByClassName("xmasBoxCon")[0];
		if (box == null) {
			return
		};
		var nextButton = document.getElementsByClassName("bnt_xmasBox")[0];
		if (nextButton != null) {
			nextButton.click();
		};
		// window.clearInterval(intervalID);
		if (box.innerHTML.indexOf("好可惜呢，这次没有中奖") < 0) {
			console.log(index + box.innerText);
		} else {
			console.log(index + " 没有中奖");
		};
		// console.log(box.innerText);
		status = "list";
		index = index + 1;
	};
};

var intervalID = window.setInterval(doNext, 1000);
status = "list";
index = 0;
console.log("Processing " + document.getElementsByClassName("char-wrapper")[0].children.length);
